var express = require("express");
var expressJwt = require("express-jwt");
const { getToken, setToken } = require("./utils/token.js");
const path = require("path");
const pug = require("pug");
// const { getDb, saveDb } = require("./utils/db.js");

var app = express();
const port = 9000;
// 解析表单请求体
app.use(express.json());
// 允许返回本地静态资源
app.use(express.static("public"));

// // 1、告诉express框架模板文件所在的位置
// app.set("views", path.join(__dirname, "views"));
// // // 2、告诉express框架模板后缀是什么
// app.set("view engine", "pug");
// // 3、当渲染后缀为art模板时，所使用的模板引擎是什么
// app.engine("pug", pug.compile);

/* 导入第三方中间件 */
let comment = require("./routes/comment");
const users = require("./routes/users");

//设置允许跨域的域名，*代表允许任意域名跨域
app.all("*", function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*"); //允许的header类型
	res.header("Access-Control-Allow-Headers", "content-type"); //跨域允许的请求方式
	res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
	if (req.method.toLowerCase() == "options") res.send(200);
	//让options尝试请求快速结束
	else next();
});

app.use((req, res, next) => {
	req.headers["authorization"] =
		"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ6aGFuZ2ppYWxpbiIsInBhc3N3b3JkIjoiMTIzIiwiaWF0IjoxNjQ3MjQ0MTg3LCJleHAiOjE2NDczMzA1ODd9.HOawlsCUSo1fhEzhbmxo5yq_85Ajvcn-jzH1M-_fCYI";
	next();
});

// 解析token获取用户信息
app.use(function (req, res, next) {
	var token = req.headers["authorization"];
	console.log("Token：", token);
	if (token == undefined) {
		return next();
	} else {
		getToken(token)
			.then((data) => {
				req.data = data;
				return next();
			})
			.catch((error) => {
				return next();
			});
	}
});

// 验证token是否过期并规定那些路由不需要验证;
app.use(
	expressJwt({
		secret: "ComprehensiveCurriculumDesign",
		algorithms: ["HS256"], // 加密算法
		credentialsRequired: false,
	}).unless({
		//用户第一次登录的时候不需要验证token
		path: ["/", "/api/login", "/api/feedback"], //不需要验证的接口名称
	})
);

// 评论模块
app.use("/api/feedback", comment);
app.use("/api/", users);

// 错误处理中间件
app.use(function (err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get("env") === "development" ? err : {};

	console.log(err);
	if (err.name === "UnauthorizedError") {
		console.error(req.path + ",无效token");
		res
			.json({
				message: "token过期，请重新登录",
				code: 400,
			})
			.end();
	}
	// render the error page
	res.status(err.status || 500);

	// res.render(pug.compileFile("./views/error.pug"));
});

app.listen(port, () => {
	console.log(`Example app listening at http://localhost:${port}`);
});

module.exports = app;
